<!DOCTYPE html>
<html lang="en" ng-app>
    <head>
        <script src="/static/js/jquery-2.0.min.js"></script>
        <script src="/static/js/jquery-ui-1.10.3.custom.min.js"></script>
        <script src="/static/js/jquery-ui-timepicker-addon.js"></script>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>

        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
        <link href="/static/css/ui-darkness/jquery-ui-1.10.3.custom.min.css" rel="stylesheet">

        <style type="text/css">
        /* TimePicker */
        /* css for timepicker */
        .ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
        .ui-timepicker-div dl { text-align: left; }
        .ui-timepicker-div dl dt { height: 25px; margin-bottom: -25px; }
        .ui-timepicker-div dl dd { margin: 0 10px 10px 65px; }
        .ui-timepicker-div td { font-size: 90%; }
        .ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }

        .ui-timepicker-rtl{ direction: rtl; }
        .ui-timepicker-rtl dl { text-align: right; }
        .ui-timepicker-rtl dl dd { margin: 0 65px 10px 10px; }
        </style>


        <style type="text/css">
            body { padding-top:40px; }
            /*tbody { display:none; }*/
            thead { cursor:pointer; }
            .tbl_ttl_btn { float:right; }
            input.column_name {  }
            .remove_col { float:right; }
            .editor_table { display:none; }
            #save { float: right; }
            .span2, .span10 { padding:10px; } 
            #holdwindow { opacity: 0.6; background: #000; position:fixed; top:0; left:0; width:100%; height:100%; color: white; text-align:center; font-size:32px; padding-top:10px; display:none; z-index: 999999; }
            input.maxmin { width:20px; }

            .red_border { color: red; font-weight: bold }
            #backuptablediv {
                background-color: white;
                padding: 10px;
                border-radius: 0px 0px 10px 10px;
                position: fixed;
                top: 40px;
                overflow:auto;
                max-height: 400px;
            }
            .top_bar { padding: 0px 10px !important; }
            .make_btn_control_smaller { margin-bottom: 0px !important; }

            #clientids_editor {  }
            .float_me_right { float:right; }

        </style>
        <title>{{ tool_name }}</title>
    </head>
    <body>
        <script type="text/javascript">
            var adm = {{ admin }};
            var gil = false;
            var avaliable_for_users = {{ user_rules }};

            var backup_manager = {
                'init': function(){

                    $.ajax({
                        type: "GET",
                        url: "/get_backups",
                        success: function(data) {
                            backup_manager.backups = data;
                            backup_manager.create_table();
                            backup_manager.events();

                        },
                        error: function(data){
                            console.log('An error ' + data.statusText + ' has occurred. Please contact your system administrator. ');
                            if(data.status != 200){
                                alert('An error ' + data.statusText + ' has occurred. Please contact your system administrator. ');
                            }
                        },
                        dataType: "json"
                    });


                },
                'backups' : {},
                'create_table': function(){
                    var cur = document.getElementById('backuptablediv');
                    if(cur != null){
                        cur.parentNode.removeChild(cur);
                    }

                    var d = document.createElement("div");
                    d.setAttribute('id','backuptablediv');
                    d.setAttribute('class', 'modal hide ');

                    var t = document.createElement("table");
                    t.setAttribute('id','backuptable');
                    t.setAttribute('class','table table-condensed table-hover ');
                    for(var bup in backup_manager.backups){
                        var row = t.insertRow(-1);
                        var cell1 = row.insertCell(0)
                        var cell2 = row.insertCell(1)
                        var cell3 = row.insertCell(2)
                        
                        var restore = document.createElement('div');
                        var remove = document.createElement('div');

                        restore.setAttribute('class', 'btn btn-small backup_restoreme add-on');
                        remove.setAttribute('class', 'btn btn-small backup_removeme add-on');

                        restore.setAttribute('data-file', backup_manager.backups[bup][0]);
                        remove.setAttribute('data-file', backup_manager.backups[bup][0]);


                        restore.innerHTML = 'Restore';
                        remove.innerHTML = 'Remove';

                        var btn_home = document.createElement('div');
                        btn_home.setAttribute('class', 'input-prepend input-append control-group make_btn_control_smaller');

                        cell2.innerHTML = bup.replace(/(\r\n|\n|\r)/gm,"<br>");
                        cell1.innerHTML = backup_manager.backups[bup][1].replace(/(\r\n|\n|\r)/gm,"<br>");

                        btn_home.appendChild(restore);
                        btn_home.appendChild(remove);
                        cell3.appendChild(btn_home);

                    };
                    d.appendChild(t);
                    doc.getElementById("content").appendChild(d);

                },

                'restoreto': function(backupname){
                    $('#holdwindow').show();
                    console.log(gil);

                    $.ajax({
                        type: "POST",
                        url: "/restore",
                        data: { 'filename': backupname },
                        success: function(data) {
                            table = data;
                            init();
                            backup_manager.init();

                            $('#holdwindow').hide();
                        },
                        error: function(data){
                            backup_manager.init();

                            if(data.status == 200){
                                table = data;
                            }

                            if(data.status != 200){
                                alert('An error ' + data.statusText + ' has occurred. Please contact your system administrator. ');
                            }
                            $('#holdwindow').hide();
                        },
                        dataType: "json"
                    });
                },

                'removeit': function(backupname){
                    $('#holdwindow').show();

                    for(var x in backup_manager.backups){
                        if (backupname == backup_manager.backups[x][0]){
                            delete backup_manager.backups[x];
                            break;
                        }
                    }


                    $.ajax({
                        type: "POST",
                        url: "/restore",
                        data: { 'filename': backupname, 'remove':'whynot' },
                        success: function(data) {
                            $('#holdwindow').hide();
                            backup_manager.init();
                            init();
                        },
                        error: function(data){
                            if(data.status != 200){
                                alert('An error ' + data.statusText + ' has occurred. Please contact your system administrator. ');
                            }
                            $('#holdwindow').hide();
                            backup_manager.init();
                            init();
                        },
                        dataType: "json"
                    });

                },

                'events': function(){
                    $('.backup_restoreme').on('click', function(){
                        backup_manager.restoreto($(this).data('file'));
                        init();
                    });

                    $('.backup_removeme').on('click', function(){
                        backup_manager.removeit($(this).data('file'));
                        init();
                    });
                }
            };

            var field_rules = {
                rules : {{ rules }},
                is_exist : function(table_name, field_name){ 
                    if(field_rules.rules[table_name] == undefined){
                        field_rules.rules[table_name] = {};
                    }
                    if(field_rules.rules[table_name][field_name] == undefined){
                        field_rules.rules[table_name][field_name] = {'min':NaN, 'max':NaN};
                        return false;
                    }
                    return true;
                },
                max : function(table_name, field_name){
                    return field_rules.rules[table_name][field_name].max;
                },
                min : function(table_name, field_name){
                    return field_rules.rules[table_name][field_name].min;
                },
                has_rule: function(table_name, field_name){
                    if( isNaN(field_rules.rules[table_name][field_name].min) && isNaN(field_rules.rules[table_name][field_name].max) ){
                        return false;
                    }
                    return true;
                },
                add_rule : function(table_name, field_name, min, max){
                    if(field_rules.rules[table_name] == undefined){
                        field_rules.rules[table_name] = {};
                    }
                    if(field_rules.rules[table_name][field_name] == undefined){
                        field_rules.rules[table_name][field_name] = {'max':NaN, 'min':NaN};
                    }
                    field_rules.rules[table_name][field_name].min = min;
                    field_rules.rules[table_name][field_name].max = max;
                },
                is_valid : function(table_name, field_name, val){
                    val = parseFloat(val);

                    var is_ok = true;
                    if(field_rules.rules[table_name][field_name] == undefined){
                        console.error("Field not found " + table_name + " " + field_name);
                        return true;
                    }

                    if(field_rules.rules[table_name][field_name].min != NaN && field_rules.rules[table_name][field_name].min != null && parseFloat(field_rules.rules[table_name][field_name].min) > val){

                        console.error("Less then min " + val);

                        is_ok = false;
                    }

                    if(field_rules.rules[table_name][field_name].max != NaN && field_rules.rules[table_name][field_name].max != null && parseFloat(field_rules.rules[table_name][field_name].max) < val){
                        console.error("Bigger then max " + val);
                        is_ok = false;
                    }


                    return is_ok;
                }
            };



            var table = {{ data }};
            var cloned_table = {};


            var doc = document;

            function len(obj){
                var keys = [];
                for(var k in obj){
                    keys.push(k);
                }
                return keys.length;
            }


            function keys(obj){
                var ks = [];
                for(var k in obj){
                    ks.push(k);
                }
                return ks;
            }


            function get_cols(obj){
                var l = 0;
                var r = 0;
                for (var i = 0; i < obj.length; i++) {
                    l = len(obj[i]);
                    if(l > r){
                        r = l;
                    }
                }

                for (var i = 0; i < obj.length; i++) {
                    l = len(obj[i]);
                    if(l == r){
                        return keys(obj[i]);
                    }
                }

                return l;
            }

            

            function create_table(data){
                var t = doc.createElement("table");
                t.setAttribute("id", 'table_' + data);
                t.setAttribute("class", "table table-bordered table-hover editor_table");
                t.setAttribute("id", data);
                var first = true;


                var row0 = t.insertRow(0);
                row0.setAttribute('class', 'info');


                for (var i = 0; i < table[data].length; i++) {
                    var k = keys(table[data][i]);
                    var all_cols = get_cols(table[data]);
                    for(var f in all_cols){
                        var exists = k.indexOf(all_cols[f]);
                        if(exists == -1){
                            k.push(all_cols[f]);
                        }
                    }
                    k = k.sort();

                    var r = t.insertRow(i + 1);
                    r.setAttribute('class', data + i);
                    var admin_col = r.insertCell(-1);
                    var remover = doc.createElement("div");
                    remover.setAttribute('class', 'btn btn-small remover adminonly');
                    remover.setAttribute('data-table', data);
                    remover.setAttribute('data-row', i);

                    remover.innerHTML='Remove Row'
                    admin_col.insertBefore(remover, admin_col.lastChild);
                    // admin_col.appendChild(remover);

                    if(data == 'game_const' || data == 'dynamic_const'){
                        var table_data_name = data;


                        // Time Picker
                        var timepicker = doc.createElement("div");
                        timepicker.setAttribute('class', 'btn btn-small timepicker adminonly');
                        timepicker.setAttribute('data-table', data);
                        timepicker.setAttribute('data-row', i);

                        timepicker.innerHTML='Datetime'
                        admin_col.insertBefore(timepicker, admin_col.lastChild);



                        if(table[data][i] == null){ console.log(data, i);  continue; }
                        field_rules.is_exist(data, table[data][i]['id']);

                        var max = '';
                        var min = '';
                        if( isNaN(field_rules.rules[data][table[data][i]['id']].max) || field_rules.rules[data][table[data][i]['id']].max == null){
                            max = '';
                        } else {
                            max = field_rules.rules[data][table[data][i]['id']].max;
                        }

                        if( isNaN(field_rules.rules[data][table[data][i]['id']].min) || field_rules.rules[data][table[data][i]['id']].min == null){
                            min = '';
                        } else {
                            min = field_rules.rules[data][table[data][i]['id']].min;
                        }

                        var is_aval = '';

                        if(avaliable_for_users[table_data_name] === undefined){
                            avaliable_for_users[table_data_name] = [];
                        }

                        if(avaliable_for_users[table_data_name].indexOf(table[data][i]['id']) !== -1){
                            is_aval = ' checked="checked" ';
                        }


                        admin_col.innerHTML +=  "<br>"+
                        "<div class='input-prepend input-append control-group adminonly'>"+
                            "<input style='width:30px;' class='add-on maxmin min' type='text' name='min' placeholder='min' value='"+ min +"'>"+
                            "<input style='width:30px;' class='add-on maxmin max' type='text' name='max' placeholder='max' value='"+ max +"'>"+
                            "<div class='btn add-on btn-small set_minmax' data-table='"+data+"' data-colname='"+table[data][i]['id']+"' >Set</div>" +
                        "</div>"+
                        "<span class='useronly'>from "+min+" to "+max+"</span>"+
                        "<div class='adminonly control-group'><input type='checkbox' class='avaliable_for_users_"+ table_data_name +"' "+is_aval+"> "+
                        "    Avaliable for users</div>" ;

                        if(adm === false && is_aval === ''){
                            admin_col.parentNode.setAttribute('style', 'display:none;');
                        }

                    }

                    
                    if(first){
                        var c0 =row0.insertCell(-1);
                        c0.innerHTML = 'Controls';
                    }


                    var col_c = 0;
                    var col_fc = 0;
                    for (var f in k) {
                        if(first){
                            var c0 =row0.insertCell(col_fc);
                            col_fc += 1;
                            field_rules.is_exist(data, k[f]);

                            if( isNaN(field_rules.rules[data][k[f]].max) || field_rules.rules[data][k[f]].max == null){
                                max = '';
                            } else {
                                max = field_rules.rules[data][k[f]].max;
                            }

                            if( isNaN(field_rules.rules[data][k[f]].min) || field_rules.rules[data][k[f]].min == null){
                                min = '';
                            } else {
                                min = field_rules.rules[data][k[f]].min;
                            }

                            c0.innerHTML = k[f] + 
                                "<div class='btn btn-small remove_col adminonly' data-table='"+data+"' data-colname='"+k[f]+"' >Remove Col</div>" +
                                "<br>";
                            if (data != 'game_const' && data != 'dynamic_const'){
                                c0.innerHTML += "<div class='input-prepend input-append control-group adminonly'>"+
                                        "<input style='width:30px;' class='add-on maxmin min' type='text' name='min' placeholder='min' value='"+ min +"'>"+
                                        "<input style='width:30px;' class='add-on maxmin max' type='text' name='max' placeholder='max' value='"+ max +"'>"+
                                        "<div class='btn add-on btn-small set_minmax' data-table='"+data+"' data-colname='"+k[f]+"' >Set</div>" +
                                    "</div>"+
                                    "<span class='useronly'>from "+min+" to "+max+"</span>";;

                            }
                        }

                        var c = r.insertCell(col_c);
                        col_c += 1;


                        c.setAttribute('class', 'editable_field');

                        c.setAttribute('contenteditable','true');
                        
                        if (table[data][i] != null && table[data][i][k[f]] != undefined){
                            c.setAttribute('data-table', data);
                            c.setAttribute('data-row', i);
                            c.setAttribute('data-field', k[f]);

                            if(k[f] == 'description'  && adm == false || k[f] == 'Description' && adm == false){
                                c.setAttribute('contenteditable', 'false');
                            }

                            if(data == 'game_const' && k[f] == 'id' && adm == false || data == 'dynamic_const' && k[f] == 'id' && adm == false){
                                c.setAttribute('contenteditable','false');
                            }


                            if( field_rules.is_valid(data, k[f], table[data][i][k[f]]) == false && data != 'game_const' && data != 'dynamic_const' ){
                                c.setAttribute('class', 'red_border');
                            }


                            if(data == 'game_const' && k[f] == 'id' || data == 'dynamic_const' && k[f] == 'id'){
                                c.setAttribute('class', '');
                                var res = field_rules.is_valid(data, table[data][i][k[f]], table[data][i]['value']);

                                if(res == false){
                                    c.setAttribute('class', 'red_border');
                                }
                            }

                            c.innerHTML = table[data][i][k[f]];
                        } else {
                            c.setAttribute('data-table', data);
                            c.setAttribute('data-row', i);
                            c.setAttribute('data-field', k[f]);                            
                        }
                    };



                    first = false;

                };


                var h = t.createTHead();
                var row=h.insertRow(0);
                var cell=row.insertCell(0);
                cell.setAttribute('colspan', 1 + len(get_cols(table[data])));

                var is_aval = '';
                if(avaliable_for_users['tables'].indexOf(data) !== -1){
                    is_aval = ' checked="checked" ';
                }

                cell.innerHTML="<b>"+data+"</b> "  + 
                    "<div class='btn remove_tbl adminonly' data-table='"+data+"'>Remove Table</div>"+
                    "<div class='input-append control-group tbl_ttl_btn adminonly'>" +
                        "<input type='text' class='span6 column_name '>" +
                        "<div class='btn insert_col' data-table='"+data+"'>+Col</div> " + 
                        "<div class='btn insert_row' data-table='"+data+"'>+Row</div> " +
                    "</div>"+
                    "<div class='adminonly control-group'><input type='checkbox' class='avaliable_for_users_table' '"+is_aval+"'> Avaliable for users</div>" ;




                var li = doc.createElement("li");
                // If not checked for users
                if(adm === false && is_aval === ''){
                    li.setAttribute('style','display:none;');
                }
                var a = doc.createElement("a");
                a.setAttribute('id', "menu_link_" + data)
                a.setAttribute('data-table', data);
                a.setAttribute('href', '#');
                a.innerHTML = data;
                li.appendChild(a);
                doc.getElementById('menu').appendChild(li);

                doc.getElementById("content").appendChild(t);
            }


            var page_to_show = 'game_const';

            function init(){
                $('#content').html('');
                $('#menu').html('');
                for (var i in table) {
                    create_table(i);
                };
                backup_manager.init();
                init_handlers();

                if(page_to_show){
                    $("#"+page_to_show).show();
                    $($('#menu_link_'+page_to_show).parent()).addClass('active');
                }

                if(adm == false){
                    $('.adminonly').hide();
                    $('.useronly').show();
                } else {
                    $('.adminonly').show();
                    $('.useronly').hide();
                }

            }


            function init_handlers(){
                $('.timepicker').on('click', function(){
                    $(this).datetimepicker({timeFormat: "hh mm tt"});

                    // var some_date = parseInt($(this.parentNode.parentNode).find('td.editable_field')[1].innerHTML, 10);
                    // var some_date = new Date(some_date*1000);
                    // $(this).datetimepicker('setDate', some_date);
                    // console.log(some_date);

                    var already_ex = $(this).find('.ui-datepicker-inline');
                    if(already_ex){
                        $(already_ex[0]).show();
                    }
                });
                $(document).on('click', '.ui-datepicker-close', function(){
                    var some_date = $(this.parentNode.parentNode.parentNode).datetimepicker('getDate');
                    var unixtime_ms = some_date.getTime();
                    var tz_offset = some_date.getTimezoneOffset() * 60;

                    var unixtime = parseInt(unixtime_ms / 1000);

                    if(tz_offset < 0){
                        unixtime = unixtime + (tz_offset * -1);
                    } else if(tz_offset > 0){
                        unixtime = unixtime + tz_offset;
                    }

                    // var field = $($(this.parentNode.parentNode.parentNode.parentNode.parentNode).find('td.editable_field')[1]);

                    var edited = $(this.parentNode.parentNode.parentNode.parentNode.parentNode).find('td.editable_field');
                    var field = edited[edited.length - 1];

                    field.innerHTML = unixtime;
                    $(this.parentNode.parentNode).hide();
                });

                /*on('click', function(){
                    console.log($($(this.parentNode.parentNode).find('td')[2]));
                    $($(this.parentNode.parentNode).find('td')[2]).datetimepicker();
                });*/


                $('#show_backups').on('click', function(){
                    $('#backuptablediv').toggle();

                });

                $('.set_minmax').on('click', function(){
                    var min = parseFloat($(this).parent().find('.min')[0].value.replace(',', '.'));
                    var max = parseFloat($(this).parent().find('.max')[0].value.replace(',', '.'));


                    if(min > max){
                        alert('Min value should be less then max.');
                        return false;
                    }

                    var tblname = $(this).data('table');
                    var colname = $(this).data('colname');
                    
                    field_rules.add_rule(tblname, colname, min, max)

                    page_to_show = tblname;
                    init();

                });

                $('#menu a').on('click', function(){
                    $('#menu li').removeClass('active');
                    $(this).parent().addClass('active');
                    $('.editor_table').hide();
                    var tbl = "#" + $(this).data('table');
                    $(tbl).show();
                });

                // $('thead').on('click', function(){
                //     $($(this).parent().find('tbody')[0]).toggle();
                // });



                $('.remover').on('click', function(){
                    var tblname = $(this).data('table');
                    var rowname = $(this).data('row');
                    if(confirm('You try to remove row, are you sure?')){
                        $("."+tblname+rowname).hide();
                        var index = table[tblname].indexOf(table[tblname][rowname]);
                        table[tblname].splice(index, 1);
                        page_to_show = tblname;
                        init();

                    }
                });

                $('.insert_row').on('click', function(){
                    var tblname = $(this).data('table');
                    table[tblname].push({});
                    page_to_show = tblname;
                    init();
                });

                $('.remove_tbl').on('click', function(){
                    var tblname = $(this).data('table');
                    if(confirm('You try to remove table ' + tblname + ', are you sure?')){
                        delete table[tblname];
                        page_to_show = false;
                        init();
                    }
                });

                $('.insert_col').on('click', function(){
                    var tblname = $(this).data('table');
                    var tbl_name = $($(this).parent().find('input')[0]).val();
                    $(this).parent().removeClass('error');
                    if(tbl_name == ''){
                        $(this).parent().addClass('error');
                        return false;
                    }
                    if(table[tblname][0] == undefined){
                        table[tblname][0] = {};
                    }
                    table[tblname][0][tbl_name] = '';
                    page_to_show = tblname;
                    init();
                    return false;
                });


                $('#create_table').on('click', function(){
                    var tbl_name = $($(this).parent().find('input')[0]).val();
                    $(this).parent().removeClass('error');
                    if(tbl_name == ''){
                        $(this).parent().addClass('error');
                        return false;
                    }
                    table[tbl_name] = Array();
                    page_to_show = tbl_name;
                    init();
                    return false;
                });

                $('.remove_col').on('click', function(){
                    var tblname = $(this).data('table');
                    var colname = $(this).data('colname');
                    if(confirm('You try to remove column ' + colname + ', from table ' + tblname + ', are you sure?')){
                        for (var i = 0; i < table[tblname].length; i++) {
                            delete table[tblname][i][colname];
                        };
                        page_to_show = tblname;
                        init();
                    }

                });

                $('body').on('focus', '[contenteditable]', function() {
                    // console.log('1', this);
                }).on('blur', '[contenteditable]', function() {
                    var tblname = $(this).data('table');
                    var rowname = $(this).data('row');
                    var fldname = $(this).data('field');
                    var val = $(this).text();
                    if (table[tblname][rowname] == null){
                        table[tblname][rowname] = {};
                    }

                    if(tblname != 'game_const' && tblname != 'dynamic_const'){
                        if(field_rules.is_valid(tblname, fldname, val) == false){
                            console.log('1 check');
                            $(this).addClass('red_border');
                            return false;                            
                        }
                    }

                    if(tblname =='game_const' && field_rules.is_valid(tblname, table[tblname][rowname]['id'], val) == false){
                        console.log('2 check', table[tblname][rowname]['id'], val, rowname, tblname);
                        $(this).addClass('red_border');
                        return false;
                    }

                    $(this).removeClass('red_border');

                    if(tblname != 'game_const' && tblname != 'dynamic_const' && fldname != 'id' &&  fldname != 'description' && fldname != 'Description'){
                        console.log('parse');
                        var new_val = "" + val.replace('\n', '').replace('\r', '');//parseFloat();

                        var has_rule = field_rules.has_rule(tblname, fldname)
                        if(has_rule){
                            var is_valid = false;
                            is_valid = field_rules.is_valid(tblname, fldname, new_val)
                            if(is_valid){
                                table[tblname][rowname][fldname] = parseFloat(new_val);
                            } else {
                                $(this).addClass('red_border');
                                return false
                            }
                        } else {

                            if(/^[a-zA-Z0-9%:._ ]+$/.test(new_val) == false){
                                $(this).addClass('red_border');
                                return false
                            }

                            table[tblname][rowname][fldname] = new_val;

                        }

                    } else {
                        console.log('no parse');
                        console.log(val);

                        if(/^[a-zA-Z0-9%:._ ]+$/.test(val) == false){
                            $(this).addClass('red_border');
                            return false
                        }
                        var new_val = "" + val.replace('\n', '').replace('\r', '');

                        table[tblname][rowname][fldname] = new_val;

                    }

                    $(this).text(table[tblname][rowname][fldname]);
                });

                $('#save').on('click', function(){
                    if (gil == true){
                        return false;
                        console.log('Global Lock');
                    }
                    gil = true;

                    var errors = $('.red_border');
                    if(errors.length > 0){
                        alert('Validation error.');
                        return true;
                    }

                    var user_table_rules = document.getElementsByClassName('avaliable_for_users_table');
                    for(var i = 0; i < user_table_rules.length; i++){

                        var table_name = user_table_rules[i].parentNode.parentNode.children[0].textContent;
                        if(user_table_rules[i].checked && avaliable_for_users['tables'].indexOf(table_name) === -1){
                            avaliable_for_users['tables'].push(table_name);
                        } else if(user_table_rules[i].checked === false && avaliable_for_users['tables'].indexOf(table_name) > -1) {
                            var ind = avaliable_for_users['tables'].indexOf(table_name);
                            avaliable_for_users['tables'].splice(ind, 1);
                        }

                    }


                    var user_const_rules = document.getElementsByClassName('avaliable_for_users_game_const');
                    for(var i = 0; i < user_const_rules.length; i++){

                        var table_name = user_const_rules[i].parentNode.parentNode.parentNode.children[1].textContent;
                        if(user_const_rules[i].checked && avaliable_for_users['game_const'].indexOf(table_name) === -1){
                            avaliable_for_users['game_const'].push(table_name);
                        } else if(user_const_rules[i].checked === false && avaliable_for_users['game_const'].indexOf(table_name) > -1) {
                            var ind = avaliable_for_users['game_const'].indexOf(table_name);
                            avaliable_for_users['game_const'].splice(ind, 1);
                        }

                    }



                    var user_const_rules = document.getElementsByClassName('avaliable_for_users_dynamic_const');
                    for(var i = 0; i < user_const_rules.length; i++){

                        var table_name = user_const_rules[i].parentNode.parentNode.parentNode.children[1].textContent;
                        if(user_const_rules[i].checked && avaliable_for_users['dynamic_const'].indexOf(table_name) === -1){
                            avaliable_for_users['dynamic_const'].push(table_name);
                        } else if(user_const_rules[i].checked === false && avaliable_for_users['dynamic_const'].indexOf(table_name) > -1) {
                            var ind = avaliable_for_users['dynamic_const'].indexOf(table_name);
                            avaliable_for_users['dynamic_const'].splice(ind, 1);
                        }

                    }




                    cloned_table = cloneObject(table);
                    for(var z in cloned_table){
                        for(var x in cloned_table[z]){
                            if (cloned_table[z][x]['description'] != undefined){
                                delete cloned_table[z][x]['description'];
                            }
                            if (cloned_table[z][x]['Description'] != undefined){
                                delete cloned_table[z][x]['Description'];
                            }
                        }
                    }


                    $('#holdwindow').show();
                    var description=prompt("Please enter description");
                    if(description == null){
                        $('#holdwindow').hide();
                        gil = false;
                        return false;
                    }

                    var save_to_svn = window.confirm("Save to SVN?");




                    $.ajax({
                      type: "POST",
                      url: "/editor",
                      data: { 
                        'data': JSON.stringify(table), 
                        'clear_data':JSON.stringify(table),/*JSON.stringify(cloned_table) , */
                        'clientid': $('#clientid').val(), 
                        'rules': JSON.stringify(field_rules.rules),
                        'avaliable_for_users': JSON.stringify(avaliable_for_users),
                        'description': description,
                        'save_to_svn': save_to_svn
                    },
                    success: function(data) {
                        console.log(data, data != 'ok')
                        if(data != 'ok'){
                            alert(data);
                        }
                        gil=false;
                        $('#holdwindow').hide();

                        backup_manager.init();

                      },
                    error: function(data){
                        if(data.responseText != 'ok'){
                            alert(data.responseText);
                        }
                        gil=false;
                        backup_manager.init();

                        if(data.status != 200){
                            alert('An error ' + data.statusText + ' has occurred. Please contact your system administrator. ');
                        }
                        
                        $('#holdwindow').hide();
                      },
                      dataType: "json"
                    });


                });
            }

            $(function(){
                init();
            });

function cloneObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
 
    var temp = obj.constructor(); // give temp the original obj's constructor
    for (var key in obj) {
        temp[key] = cloneObject(obj[key]);
    }
 
    return temp;
}
</script>

<script>
function WhiteList($scope, $http) {
    $scope.clientids = [];

    $scope.init = function () {
        $scope.load();
    };

    $scope.addClientid = function() {
        $scope.clientids.push({text:$scope.some_clientid});
        $scope.some_clientid = '';
    };

    $scope.removeClientid = function(idx) {
        var clidtoremove = $scope.clientids[idx];
        $scope.clientids.splice(idx, 1);
    };

    $scope.save = function() {

        $.ajax({
            type: "POST",
            url: "/save_avaliabe_ids",
            data: { 
                'data': JSON.stringify($scope.clientids),
            },
            success: function(data) {
            },
            error: function(data){
            }
            // , dataType: "json"
        });
    };

    $scope.load = function() {
        $.ajax({
            type: "GET",
            url: "/load_avaliabe_ids",
            success: function(data) {
                $scope.replace_from_load(data);
            },
            error: function(data){
                console.log('err');
            }, 
            dataType: "json"
        });
    };

    $scope.replace_from_load = function(data){
        $scope.clientids = [];
        for (var i = 0; i < data.length; i++) {
            $scope.clientids.push({text:data[i]['text']});                    
        };
        $scope.$apply();
    };

}


</script>




<div class="navbar navbar-inverse navbar-fixed-top clearfix ">
    <div class="navbar-inner top_bar">
          <a class="brand" href="/editor">&nbsp;{{ tool_name }}</a>
          <div class=' control-group '>
              
              <div class='btn btn-primary' id='save'>Save</div>
          </div>
    </div>
</div>


<div class="row-fluid clearfix">
    <div class="span2">

{% raw %}
<h3 class='adminonly'>Client Id WhiteList</h3>
<div id="clientids_editor" class='adminonly' ng-controller="WhiteList" data-ng-init="init()">
    <ul class="nav nav-tabs nav-stacked">
        <li ng-repeat="clientid_agjs in clientids">
            <a href='#'>{{clientid_agjs.text}} 
                <i class="icon-remove float_me_right" ng-click="removeClientid($index)"></i>

            </a>
            
        </li>
    </ul>

    <form ng-submit="addClientid()">
            <input type="text" ng-model="some_clientid"  size="30"
               placeholder="add new clientid here"><br>

        <div class=' btn-group '>
            <input class="btn btn-small " type="submit" value="Add">
            <div class="btn btn-small " ng-click="save()" value="">Save</div>
            <div class="btn btn-small " ng-click="load()" value="">Load</div>
        </div>
    </form>

</div>
{% endraw %}


        <h3 class='adminonly'>Client Id</h3>
        <input class='adminonly' type="text" placeholder="ClientId" id='clientid' value='{{ clientid }}'>
        <h3>Tables</h3>
        <ul class="nav nav-pills nav-stacked" id='menu'>
        </ul>

        <div class='input-append control-group tbl_ttl_btn span12 adminonly'> 
            <input type='text' class='span6 table_name '> 
            <div class='btn' id='create_table'>Create table</div>   
        </div>

        <h3 class=''>Backups</h3>
        <div>
            <div class='btn' id='show_backups'>Backups</div>
        </div>

        <h3 class=''>Logout</h3>
        <div>
            <a class='btn' href='/logout' >Logout</a>
        </div>

    </div>
    <div class="span10">
        <div id="content"></div>
        
    </div>

</div>


<div id='holdwindow'>Saving...</div>
    </body>
</html>

